package com.cheng.dreams.sample.net;


import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;

public final class NetClient {
    static final int TIME_OUT = 10 * 1000;
    static final String TEST = "http://kingblog.imwork.net/wszh/";
    public static final String BASE_URL = TEST;
    static final String token="ojARF/d3kVoPp3O7+gwZnmLgKtnqyzUgxVJ61v+Eq4YqKcBmVJfAc/dGouwDVFD3";
    private NetClient() {
    }
    public static ApiService getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private static class SingletonHolder {
        private static final ApiService INSTANCE = create().create(ApiService.class);

        private static Retrofit create() {
            return new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(getHttpClient())
                    .addConverterFactory(MyGsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
    }

    private static OkHttpClient getHttpClient() {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
                .readTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request()
                                .newBuilder()
                                .addHeader("platform", "1")
                                .addHeader("token",token)
                                .build();
                        return chain.proceed(request);
                    }
                })
                .build();
        return client;
    }

}
